<template>
  <div class="staff-list">
    <div ref="dgtools" class="filter-container">
      <div class="dgts-fm">
        <el-input v-model="dg.ps.find" placeholder="姓名/电话" style="width: 200px" />
        <!-- <el-select
          v-model="dg.ps.deptIds"
          placeholder="选择部门"
          style="width: 200px"
          clearable
        >
          <el-option
            v-for="item in departmentOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>  -->

        <SelTeamGroup :tipText="'请选择部门'" :deptNames="''" :width="210" @selItem="getSeledTeamGroup" :isMult="true"
          :isSelAny="true">
        </SelTeamGroup>

        <el-select v-model="dg.ps.roleIds" style="width: 200px" clearable placeholder="报账角色选择">
          <el-option v-for="item in roleOptions" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>

        <!-- <el-select
          v-model="dg.ps.groupIds"
          placeholder="选择小组"
          style="width: 200px"
          clearable
        >
          <el-option
            v-for="item in groupOptions"
            :key="item.id"
            :label="item.groupName"
            :value="item.id"
          ></el-option>
        </el-select> -->
        <el-select v-model="dg.ps.staffState" placeholder="在职状态" style="width: 200px" clearable>
          <el-option label="正式" value="NORMAL"></el-option>
          <el-option label="试用" value="TRY"></el-option>
          <el-option label="离职" value="LEAVE"></el-option>
        </el-select>

        <el-button type="primary" icon="el-icon-search" @click="getDgList">
          搜索
        </el-button>
      </div>
      <div>
        <el-button type="primary" icon="el-icon-plus" @click="getAddMdState(true)">
          新增
        </el-button>

        <el-button type="primary" icon="el-icon-edit-outline " @click="getUpdMdState(true)">
          修改
        </el-button>

        <el-button type="primary" icon="el-icon-s-check" @click="setLeaveOfficeMd({ state: true })">
          员工离职
        </el-button>

        <el-button type="primary" icon="el-icon-setting" @click="setSetMoneyTypeMd({ state: true })">
          设置金额类型
        </el-button>

        <el-button type="primary" icon="el-icon-delete" @click="deleteStaff">
          删除
        </el-button>

        <el-button type="primary" icon="el-icon-printer" @click="print">
          导出
        </el-button>
      </div>

      <TableSelfSet v-if="dg.columns.length > 0" :tbTitle="'员工列表'" :dgName="dg.dgName" :tbId="dg.tbName"
        :srcCols="dg.srcCols" :columns="dg.columns" @saveSet="saveTbSet" />
    </div>
    <el-table :ref="dg.tbName" :data="dg.list" row-key="id" :height="bodyHeight" border fit :row-class-name="rowClassName"
      @selection-change="selRowChange">
      <el-table-column fixed="left" type="selection" width="40">
      </el-table-column>

      <fragment v-for="col in dg.columns" :key="col.field">
        <el-table-column :class-name="dg.dgName" :prop="col.field" :label="col.label" :width="col.width">
          <template slot-scope="{ row }">
            <template v-if="col.field == 'linkPhone'">{{ row.driverInfo ? "是" : "否" }}</template>
            <template v-else-if="col.field == 'staffState'">{{ staffStateFilter(row) }}</template>
            <template v-else-if="col.field == 'idCardUrl'">
              <div class="idCard-wrapper">
                <img class="idCard" v-for="(item, index) in getImage(row)" :key="index" :src="fileBaseUrl + item" />
              </div>
            </template>
            <template v-else-if="col.field == 'education'">{{ educationFilter(row) }}</template>
            <template v-else-if="col.field == 'lookBtlBalance'">{{ row.lookBtlBalance ? "是" : "否" }}</template>
            <template v-else>{{ getColVal(row, col.field) }}</template>
          </template>
        </el-table-column>
      </fragment>
    </el-table>
    <pagination v-show="dg.total > 0" :total="dg.total" :page.sync="dg.ps.page" :limit.sync="dg.ps.rows"
      @pagination="getDgList" />

    <AddStaff v-if="md.add.state" :state="md.add.state" @getMdState="resizeData" @reloadDg="getDgList" />

    <UpdateStaff v-if="md.upd.state" :state="md.upd.state" :id="currentId" @getMdState="resizeData"
      @reloadDg="getDgList" />

    <!-- <leaveOfficeType
      v-if="md.leave.state"
      :state="md.leave.state"
      :id="currentId"
      @getMdState="resizeData"
      @reloadDg="getDgList"/> -->

    <LeaveOfficeType v-if="leaveOfficeMd.state" :id="currentId" @myClick="setLeaveOfficeMd" @reloadDg="getDgList" />

    <SetMoneyType v-if="setMoneyTypeMd.state" :myData="setMoneyTypeMd" @myClick="setSetMoneyTypeMd"
      @reloadDg="getDgList" />
  </div>
</template>
<script>
import DataGridBase from "@/views/mixins/DataGridBase";
import DataGridResize from "@/views/mixins/DataGridResize";
import elDragDialog from "@/directive/el-drag-dialog";
import TableSelfSet from "@/components/TableSelfSet";
import Pagination from "@/components/Pagination";

import SelTeamGroup from '@/components/SelTeamGroup';
import { staffStateEnum, educationEnum } from "@/utils/stateMap";
import AddStaff from "./add-staff";
import UpdateStaff from "./update-staff";
import LeaveOfficeType from "./leave-office-type";
import SetMoneyType from "./set-money-type";

import { getStaffList, deleteStaff } from "@/api/services/personMan.service";
import { getFindDepts, getGroupDict, getRoleByDeptId } from "@/api/services/common.service";

export default {
  name: 'StaffList',
  mixins: [DataGridBase, DataGridResize],
  directives: { elDragDialog },
  components: {
    TableSelfSet,
    Pagination,
    SelTeamGroup,
    AddStaff,
    UpdateStaff,
    LeaveOfficeType,
    SetMoneyType,
  },
  data() {
    let cols = [
      { label: "单位编号", field: "unitNum", width: 80 },
      { label: "姓名", field: "baseUserId.realName", width: 80 },
      { label: "电话", field: "baseUserId.phone", width: 90 },
      { label: "驾驶员", field: "linkPhone", width: 50 },
      { label: "入职状态", field: "staffState", width: 70 },
      { label: "身份证(正反)", field: "idCardUrl", width: 140 },
      { label: "入职公司", field: "entryCompany.companyName", width: 180 },
      { label: "入职时间", field: "entryTime", width: "auto" },
      { label: "合同到期时间", field: "expireTime", width: 90 },
      { label: "所属部门", field: "deptId.name", width: 70 },
      { label: "角色/职务", field: "roleId.name", width: 70 },
      { label: "添加时间", field: "addTime", width: 130 },
      { label: "住宿地址", field: "stayAddress", width: 140 },
      { label: "学历", field: "education", width: 140 },
      { label: "是否查看银行账余额", field: "lookBtlBalance", width: 140 },
    ];

    return {
      // 文件地址前缀
      fileBaseUrl: this.C.fileBaseUrl,
      dg: {
        dgName: "dg",
        tbName: "staffListTb",
        total: 0,
        list: [],
        srcCols: cols,
        columns: [],
        selRows: [],
        ps: {
          // 过滤参数
          page: 1, rows: 20,
          find: "",
          deptIds: [], // 部门id
          // groupIds: "", // 小组id
          roleIds: "", //角色id
          staffState: "", // 入职状态
        },
      },
      md: {
        // 弹框数据
        add: { state: false },
        upd: { state: false },
      },
      // 设置金额类型-弹框
      setMoneyTypeMd: { state: false },

      // 离职处理-弹框
      leaveOfficeMd: { state: false },
      currentId: null,
      roleOptions: [],
      // departmentOptions: [], // 部门
      // groupOptions: [], // 小组
    };
  },
  created() {
    this.initTbSetData(this.dg.dgName);
    this.getDgList();
    // this.getDictInfo();
  },
  methods: {
    // 获取-表格数据列表
    getDgList() {
      let that = this, ps = that.U.scopy(that.dg.ps);

      ps.deptIds = ps.deptIds.join(',');
      getStaffList(ps).then((res) => {
        const { code, data, count } = res;
        if (code === 1) {
          let list = data;
          list.forEach((it) => { it.dgName = that.dg.dgName; });
          that.dg.list = list;
          that.dg.total = count;
        }
      });
    },
    // 获取下拉所需数据
    getDictInfo() {
      // let params = { page: 1, rows: 9999 };
      // getFindDepts(params).then((res) => {
      //   this.departmentOptions = res.data;
      // });
      // // 获取小组下拉列表
      // let groupParams = { teamId: "" };
      // getGroupDict(groupParams).then((res) => {
      //   this.groupOptions = res.data;
      // });
      // 获取角色
      // let roleParams = { deptId: "" };
      // getRoleByDeptId(roleParams).then((res) => {
      //   this.roleOptions = res.data;
      // });
    },
    // 获取选中-部门数据
    getSeledTeamGroup(e) {
      this.U.setFmArr(this.dg.ps.deptIds, e.val);

      // 获取报账角色选择

      let data = e.val.join(',')
      let roleParams = { deptId: data || 0 };
      getRoleByDeptId(roleParams).then((res) => {
        this.roleOptions = res.data;
        console.log(this.roleOptions, 'this.roleOptions')
      });

    },
    getImage(data) {
      if (!data) return [];
      return data.idCardUrl?.split(",");
    },
    staffStateFilter(row) {
      return staffStateEnum[row.staffState] || "-";
    },
    educationFilter(row) {
      return educationEnum[row.education] || "-";
    },
    // 设置金额类型
    setSetMoneyTypeMd(e) {
      const that = this, U = that.U, rows = that.getSeledRows(), md = that.setMoneyTypeMd;

      if (!e.state) {
        md.state = false;
      } else {
        if (rows.length != 1) {
          U.qerror(`${rows.length == 0 ? '请' : '只能'}选择一条数据`);
        } else {
          let row = rows[0];

          let arr = [];
          if (row.moneyTypeIdName) {
            row.moneyTypeIdName.split(',').forEach(it => {
              arr.push(it.split('-')[0]);
            });
          }
          md.obj = {
            mtIds: arr,
            id: row.id,
          };
          md.state = true;
        }
      }
    },
    // 员工离职
    setLeaveOfficeMd(e) {
      const that = this, U = that.U, rows = that.getSeledRows();

      if (!e.state) {
        that.leaveOfficeMd.state = false;
      } else {
        if (rows.length != 1) {
          U.qerror(`${rows.length == 0 ? '请' : '只能'}选择一条数据`);
        } else {
          let row = rows[0];
          if (row.staffState == 'LEAVE') {
            U.qerror('此员工已离职，请重新选择');
          } else {
            that.currentId = row.id;
            that.leaveOfficeMd.state = true;
          }
        }
      }
    },
    getAddMdState(e) {
      this.md.add.state = e;
    },
    // 清除所有列表选中项，且关闭所有操作弹框
    resizeData() {
      let eleRef = this.dg.tbName;
      this.$refs[eleRef].clearSelection();
      this.md = {
        add: { state: false },
        upd: { state: false },
      };
    },
    getUpdMdState(e) {
      const that = this, U = that.U, rows = that.getSeledRows();

      if (rows.length != 1) {
        U.qerror(`${rows.length == 0 ? '请' : '只能'}选择一条数据`);
      } else {
        that.currentId = rows[0].id;
        that.md.upd.state = true;
      }
    },
    print() {
      this.U.qinfo('抱歉，功能待完善！');
    },
    // 删除员工
    deleteStaff() {
      const that = this, U = that.U, rows = that.getSeledRows();

      if (rows.length != 1) {
        U.qerror(`${rows.length == 0 ? '请' : '只能'}选择一条数据`);
      } else {
        let row = rows[0];
        if (row.staffState != 'LEAVE') {
          U.qerror('所选员工未离职，不能删除');
        } else {
          that.currentId = row.id;
          U.qconfim('您确认删除所选员工吗？', '删除询问').then(r => {
            if (r) {
              deleteStaff({ id: row.id }).then((res) => {
                if (res.code != 1) {
                  U.qerror(res.msg);
                } else {
                  U.qsuccess(res.msg);
                  that.getDgList();
                }
              });
            }
          });
        }
      }
    },


  },

};
</script>
<style lang="less" scoped>
.filter-container>* {
  display: block;
}

.idCard-wrapper {
  display: inline-flex;

  & img:first-child {
    margin-right: 10px;
  }

  .idCard {
    width: 50px;
    height: 36px;
  }
}
</style>
